<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\common\Util;
use plugin\admin\app\constant\v1\CommonConstant;
use support\Request;
use support\Response;
use plugin\admin\app\model\V1OrderNode;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 订单节点调换记录
 */
class V1OrderNodeExchangeController extends Crud
{
    /**
     * 无需登录及鉴权的方法
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 需要登录无需鉴权的方法
     * @var array
     */
    protected $noNeedAuth = [
        'select'
    ];
    
    /**
     * @var V1OrderNode
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new V1OrderNode;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(Request $request): Response
    {

        $order_id = $request->input('order_id');
        $user_id = $request->input('user_id');
        return view('v1-order-node-exchange/index', compact('order_id','user_id'));
    }

    /**
     * 查询
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $admin = admin();
        if ($admin['user_status'] == CommonConstant::DEFAULT_2) {
            $where['user_id'] = $admin['id'];
        }
        $where['deleted'] = CommonConstant::DELETE_0;
        $where['exchange_number'] = ['>',0];
        $query = $this->doSelect($where, $field, $order);
        $query->with([
            'server' => function ($query) {
                $query->where('deleted', CommonConstant::DELETE_0)
                    ->select(['id','multi_port_status','multi_port']);
            }
        ]);
        $paginator = $query->paginate($limit);
        $total = $paginator->total();
        $items = $paginator->items();
        if ($items) {
            foreach ($items as $item) {
                Util::getSk5Port($item);
            }
        }
        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
        return $this->doFormat($query, $format, $limit);
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('v1-order-node-exchange/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('v1-order-node-exchange/update');
    }

}
